#include "http_post.h"


// reply of the requery
static size_t req_reply(void *ptr, size_t size, size_t nmemb, void *stream)
{
	std::cout << "----->reply" << std::endl;
	std::string *str = (std::string*)stream;
	std::cout << *str << std::endl;
	(*str).append((char*)ptr, size*nmemb);
	return size * nmemb;
}

HttpPost::HttpPost()
{
    printf("HttpPost Constructor\n");
    curl_global_init(CURL_GLOBAL_ALL);
}

HttpPost::~HttpPost()
{
    printf("~HttpPost Destructor\n");
    curl_global_cleanup();
}


bool HttpPost::curlPostReq(const std::string& url,const std::string &postParams)
{
    // init curl
	CURL *curl = curl_easy_init();
	// res code
	CURLcode res;
    std::string postResponseStr;
	//HTTP报文头  
    // struct curl_slist* headers = NULL;
	if (curl)
	{
		// set params
		curl_easy_setopt(curl, CURLOPT_POST, 1); // post req
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // url
		//构建HTTP报文头  
        //使用模拟的header头设置HTTP请求的头信息
        // headers=curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");
        
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers_);

		//post请求参数设置，get方法的参数可以在url中体现，post的参数必须在此处设置，参数格式如下"name=daniel&project=curl"
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str()); // params

		// https请求 不验证证书和hosts
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); // if want to use https
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); // set peer and host verify false
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
		curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);

		 //传递调用完成时的回调函数
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
        
		//回调函数第四个参数
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&postResponseStr);

		//关闭中断信号响应，如果是多线程，请将该参数置为1。这个选项用于unix环境下的多线程应用仍然可以使用各种timeout选项，而不会引发信号中断致使程序退出。
		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

		 //告诉libcurl在输出请求体时包含头部信息
		curl_easy_setopt(curl, CURLOPT_HEADER, 1);
		//设置连接超时时长（秒）
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
		//请求超时时长（秒）
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
		// start req //执行请求
		res = curl_easy_perform(curl);

        if(res != CURLE_OK){
            printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            return false;
        }
        printf("=============================\n");
        printf("postResponseStr:%s\n", postResponseStr.c_str());
        if(replyProcessCall_)
            replyProcessCall_(postResponseStr);
        else
            printf("please register callback!!!\n");
	}

    
	// release curl
	curl_easy_cleanup(curl);
    return true;
}
